﻿using System;
using System.Management;
using Aspects.PInvoke;

namespace Aspects.Unit
{
    class HddInfo
    {
        public static HardDrive GetHddInfo()
        {
            var hdd = new HardDrive();
            hdd.Name = "Not Working Yet";
            hdd.Firmware = "Not Working Yet";
            hdd.Capacity = "0Gb";

            bool Windows7 = Aspects.Unit.OS.getMajorVersion()==6;
            PopulateHddInformation(ref hdd, Windows7);
            return hdd;
        }

        private static void PopulateHddInformation(ref HardDrive hdd, bool win7)
        {
            var wmiInformation = new ManagementObject(@"\\.\root\cimv2:Win32_DiskDrive='\\.\PhysicalDrive0'");
            var pinvokeInformation = Native.GetHddIdentification();
            Console.WriteLine("HDD Model:{0}", GetReversedString(pinvokeInformation.sModelNumber));
            Console.WriteLine("HDD Serial:{0}", GetReversedString(pinvokeInformation.sSerialNumber));
            Console.WriteLine("HDD Firmware:{0}", GetReversedString(pinvokeInformation.sFirmwareRev));
                              
            hdd.Name = wmiInformation["Model"].ToString();

            if (win7)
            {
                hdd.Firmware = wmiInformation["FirmwareRevision"].ToString();
            }
            else
            {
                hdd.Firmware = GetReversedString(pinvokeInformation.sFirmwareRev);
            }
            ulong bytes;
            ulong.TryParse(wmiInformation["Size"].ToString(), out bytes);
            hdd.Capacity = BytesToGigabytes(bytes);

        }

        private static string BytesToGigabytes(ulong bytes)
        {
            if (bytes == 0)
                return "0 GB";
            else
            {
                bytes /= 1000; //bytes > kilobytes
                bytes /= 1000; //kilobytes > megabytes
                bytes /= 1000; //megabytes > gigabytes
                return bytes + " GB";
            }
        }
        
        private static string GetReversedString(byte[] data)
        {
            byte[] switched = new byte[data.Length];
            for (int i = 0; i < data.Length; i++)
            {
                switched[i++] = data[i];
                switched[i] = data[i-1];
            }
            return System.Text.ASCIIEncoding.ASCII.GetString(switched).Trim();
        }
    }
}
